package cn.zyq.demo.system.exception;

import cn.zyq.demo.system.enums.core.ResponseCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@ControllerAdvice
public class ExceptionHandle {

    @ExceptionHandler
    @ResponseBody
    public Object handle(Exception e) {
        Map map = new HashMap();
        if (e instanceof BusinessException) {
            BusinessException exception = (BusinessException) e;
            map.put("code", exception.getCode());
            map.put("msg", exception.getMsg());
            if (!exception.getCode().equals(ResponseCodeEnum.SUCCESS.getCode())) {
                log.error(exception.getMsg(), exception);
            }
        } else {
            map.put("code", ResponseCodeEnum.ERROR.getCode());
            map.put("msg", ResponseCodeEnum.ERROR.getMsg());
            log.error(e.getMessage(), e);
        }
        return map;
    }
}
